<template>
  <div class="topbar">
    <div class="wrap">
      <div class="l">欢迎来到E兑乐积分商城</div>
      <div class="r">
        <ul>
          <li @click="hdClick">
            <img :src="userInfo.headImg" alt="" />
            用户名：{{ userInfo.nickName }}
          </li>
          <li>我的积分:{{ userInfo.coin }}</li>
          <li>获取积分</li>
          <li>E兑乐官网</li>
          <li class="login Btn" @click="changeIsShowLoginModal(true)" v-show="!IsLogin">
            登录
          </li>
          <li class="cart Btn" v-show="IsLogin">
            <img src="@/assets/img/cart.png" alt="" />购物车
            <i>{{ cartTotal }}</i>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { WeiXinLoginAPI } from "@/request/api";
export default {
  data() {
    return {};
  },
  watch: {
    //监听路径的变化
    "$route.path": {
      handler(oldVal, newVal) {
        console.log(oldVal, newVal);
        //判断是否存在token
        let myToken = localStorage.getItem("x-auth-token");
        //如果存在Boolean(myToken)为true，否则为false 调用changeIsLogin改变登录状态
        this.changeIsLogin(Boolean(myToken));
        if (myToken) {
          //如果有token端发起请求获取用户信息
          this.asyncChanUserInfo();
        } else {
          //没有token则初始化用户信息
          this.initUserInfo();
        }
      },
    },
  },
  created() {
    setTimeout(async () => {
      //先判断地址栏有没有code
      let mycode = this.$route.query.code;
      if (mycode) {
        //发起微信扫码登录请求
        let res = await WeiXinLoginAPI({
          code: mycode,
        });
        console.log("WeiXinLoginAPI----", res);

        /* 对三种情况做不同的处理 */

        if (res.code == 0) {
          /* 1.微信扫码登录成功 */

          //1.提示登录成功
          this.asyncChangeIsShowToast({
            /* 调用Vuex 中 asyncChangeIsShowToast给一个对象 */
            msg: "登录成功",
            type: "success",
          });
          //3.保存后端返回token值
          localStorage.setItem("x-auth-token", res["x-auth-token"]);
          //4.用户登录状态切换
          this.changeIsLogin(true);
          //5.刷新当前路径进行删除code
          this.$router.push(this.$route.path);
          //6.向后端发起请求获取用户信息
          this.asyncChanUserInfo();
          console.log("微信扫码登录成功", res);
        } else if (res.code == 400) {
          /* 2.code失效 */
          console.log("code失效----", res);
          //(1)提示用户重新扫码
          this.asyncChangeIsShowToast({
            msg: "请重新扫码",
            type: "danger",
          });
          //(2)把登录框打开
          this.changeIsShowLoginModal(true);
          console.log("code失效请重新扫码");
        } else if (res.code == 407) {
          /* 3.微信号，没有绑定手机号 */

          //(1)提示用户没有绑定手机号,请先用手机号登录
          this.asyncChangeIsShowToast({
            msg: "请先用手机号登录绑定微信",
            type: "warning",
          });
          //(2)把登录框打开
          this.changeIsShowLoginModal(true);
          //(3)把uuid保存到localStorage
          localStorage.setItem("uuid", res.uuid);
          console.log("微信号，没有绑定手机号,请先用手机号登录");
        }
      } else {
        //没有code的情况-----1.用户没有扫码登录 2.加载这个页面的时候用户已经到了了
        //判断是否存在token
        let myToken = localStorage.getItem("x-auth-token");
        //如果存在Boolean(myToken)为true，否则为false 调用changeIsLogin改变登录状态
        this.changeIsLogin(Boolean(myToken));
        if (myToken) {
          //如果有token端发起请求获取用户信息
          this.asyncChanUserInfo();
        } else {
          //没有token则初始化用户信息
          this.initUserInfo();
        }
      }
    }, 100);
  },
  computed: {
    ...mapState({
      IsLogin: (state) => state.loginStatus.IsLogin,
      userInfo: (state) => state.userInfo.userInfo,
      cartTotal: (state) => state.userInfo.cartTotal,
    }),
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showLogin/changeIsShowLoginModal",
      changeIsShowToast: "ToastStatus/changeIsShowToast",
      changeIsLogin: "loginStatus/changeIsLogin",
      //如果没有token显示默认的用户信息
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "ToastStatus/asyncChangeIsShowToast",
      asyncChanUserInfo: "userInfo/asyncChanUserInfo",
    }),
    //点击用户名
    hdClick() {
      //调用asyncChangeIsShowToast给一个对象
      //success 成功
      //warning 警告
      //danger 失败
      //判断是否存在token
      let myToken = localStorage.getItem("x-auth-token");
      //如果存在Boolean(myToken)为true，否则为false 调用changeIsLogin改变登录状态
      this.changeIsLogin(Boolean(myToken));
      if (myToken) {
        //如果跳转到用户信息页面
        this.$router.push('/user');
      } else {
        //没有token提示
        this.asyncChangeIsShowToast({
          msg: "请先登录！",
          type: "warning",
        });
      }


    },
  },
};
</script>

<style lang="less" scoped>
@import "../assets/css/global.less";

.topbar {
  height: 40px;
  background: #242b39;
  /*字体样式  */
  font-size: 16px;
  font-family: SourceHanSansSC;
  font-weight: 300;
  color: #fffefe;
  line-height: 40px;

  .wrap {
    height: 40px;
    display: flex;
    justify-content: space-between;

    .r ul {
      display: flex;

      li {
        display: flex;
        align-items: center;
        margin-left: 20px;
        cursor: pointer;

        img {
          width: 26px;
          border-radius: 50%;
          margin-right: 6px;
        }

        &.Btn {
          width: 124px;
          height: 40px;
          background: #0C4FA6;
          justify-content: center;
        }

        &.cart {
          i {
            width: 22px;
            height: 22px;
            background: #fd604d;
            border-radius: 11px;
            line-height: 22px;
            text-align: center;
            margin-left: 5px;
          }
        }
      }
    }
  }
}
</style>